import {AfterViewInit, Component, Input, OnInit, ViewChild} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {BaseService, ReturnForm} from '@sb/base';
import {RmRoleService} from '../../rm-role/service/rm-role.service';
import {RmMenuTreePanelComponent} from '../../rm-menu/rm-menu-tree-panel/rm-menu-tree-panel.component';
import {RmRoleMenuService} from '../service/rm-role-menu-tree.service';
import {RmMenuTreeService} from '../../rm-menu/service/rm-menu-tree.service';
import {of, timer} from 'rxjs';

@Component({
    selector: 'rm-role-menu',
    templateUrl: './rm-role-menu.component.html',
    styleUrls: ['./rm-role-menu.component.less'],
    providers: [
        {
            provide: BaseService,
            useClass: RmRoleMenuService
        }
    ]
})
export class RmRoleMenuComponent implements OnInit, AfterViewInit {

    showDetailPanel = false;

    searchConfig: { roleId?: string, [key: string]: any } = {
        roleId: ''
    };

    @ViewChild('roleMenuTree', {static: false})
    roleMenuTree: RmMenuTreePanelComponent;

    @ViewChild('checkedMenuTree', {static: false})
    checkedMenuTree: RmMenuTreePanelComponent;

    @Input()
    checkable = false;

    @Input()
    checkedWhileClick = true;

    @Input()
    checkedKeys = [];
    private _viewInit = false;

    constructor(
        private message: NzMessageService,
        private rmRoleService: RmRoleService,
        private rmRoleMenuService: RmRoleMenuService
    ) {
    }

    private _roleId = '';

    get roleId() {
        return this._roleId;
    }

    @Input()
    set roleId(roleId: string) {
        if (roleId) {
            this.searchConfig.roleId = roleId;
        } else {
            this.searchConfig.roleId = '';
        }
        this._roleId = roleId;
        if (this._viewInit) {
            if (this.roleMenuTree) {
                this.roleMenuTree.reload();
            }
        } else {
            timer(100).subscribe(value => {
                if (this.roleMenuTree) {
                    this.roleMenuTree.reload();
                }
            });
        }
    }

    ngAfterViewInit(): void {
        this._viewInit = true;
    }

    ngOnInit(): void {
    }

    collapsed(): void {
        const allNodeList = this.roleMenuTree.baseTree.nzTree.getTreeNodes();
        for (const treeNode of allNodeList) {
            treeNode.isExpanded = false;
        }
        this.roleMenuTree.baseTree.nzTree.nzExpandAll = false;
    }

    expanded(): void {
        this.roleMenuTree.baseTree.nzTree.nzExpandAll = true;
    }

    refresh(): void {
        this.roleMenuTree.baseTree.reload();
    }

    commitMenu(): void {
        this.showDetailPanel = true;
        timer(200).subscribe(value => {
            const allNodeList = this.roleMenuTree.baseTree.nzTree.getTreeNodes();
            const menuIds = this.getMenuIds(allNodeList);
            this.checkedMenuTree.checkNodeIds(menuIds);
        });
    }

    submit() {
        const checkedNodeList = this.checkedMenuTree.baseTree.nzTree.getCheckedNodeList();
        const checkMenuIds = this.getCheckedMenuIds(checkedNodeList);
        if (!this.roleId) {
            this.message.error('请选择角色');
            return;
        }
        this.rmRoleMenuService.updateRoleMenu(this.roleId, checkMenuIds).subscribe(returnForm => {
            if (returnForm.success) {
                this.showDetailPanel = false;
                this.roleMenuTree.baseTree.reload();
                this.message.success('保存成功！');
            } else {
                this.message.error('获取角色失败：' + returnForm.errorMessage);
            }
        });
    }

    getCheckedMenuIds(data): string[] {
        const result: string[] = [];
        if (!data || !data.length) {
            return result;
        }
        for (let i = 0; i < data.length; i++) {
            if (data[i].origin.checked &&
                (data[i].origin.type === 'MENU' || data[i].origin.type === 'PERMISSION')) {
                result.push(data[i].key);
            }
            // const childs = data[i].children;
            // if (childs && childs.length > 0) {
            //     result.push(...this.getCheckedMenuIds(childs));
            // }
        }
        return result;
    }

    getMenuIds(data): string[] {
        const result: string[] = [];
        if (!data || !data.length) {
            return result;
        }
        for (let i = 0; i < data.length; i++) {
            if (data[i].isLeaf) {
                result.push(data[i].key);
            }
            const childs = data[i].children;
            if (childs && childs.length > 0) {
                result.push(...this.getMenuIds(childs));
            }
        }
        return result;
    }

    customLoadMethod(parentId: string, searchConfig: any, maxLevel: number, rmMenuTreeService: RmMenuTreeService) {
        if (searchConfig.roleId === '-1') {
            return of({
                success: false,
                errorMessage: '无数据'
            } as ReturnForm<any[]>);
        }
        return this.rmRoleMenuService.getMenuNzTree(searchConfig.roleId);
    }


    closeClick() {
        this.showDetailPanel = false;
    }
}
